/**
 * Created by Peter on 2015-06-01.
 */
var OutlerCenterApp = {};

var WxStoreApp = angular.module('OutlerCenterApp', ['ionic', 'OutlerCenterApp.filters', 'OutlerCenterApp.services', 'OutlerCenterApp.directives', 'ngDialog', 'tabSlideBox']);

/**
 * 问题：用户登录失效时的Ajax请求错误。直接得到login页面，而不是相应的业务数据。
 * 问题分析：当用户登录信息失效，这时的浏览器会得到302相应，并且浏览器会直接重定向到应用指定的[login URL]，然后Angularjs $http直接得到[login URL]的200相应。
 *          因此angularjs $http 的error函数并不会被调用，因为得到的是200，并且数据是登录页面的html。
 * 解决：使用拦截器，全局拦截 http的response，如果发现是登录页的html，让浏览器重定向到登录页面。
 */
WxStoreApp.factory('oauthInterceptor', ['$location', '$q', "$rootScope", function($location, $q, $rootScope) {
	return {
	    // All the following methods are optional
	    request: function(config) {
	      // Called before send a new XHR request.
	      // This is a good place where manipulate the
	      // request parameters.

	      return config || $q.when(config);
	    },

	    requestError: function(rejection) {
	      // Called when another request fails.

	      // I am still searching a good use case for this.
	      // If you are aware of it, please write a comment

	      return $q.reject(rejection);
	    },

	    response: function(response) {
	    	//console.log("oauthInterceptor response");
	        // Called before a promise is resolved.
	    	if (typeof response.data === 'string') {
                if (response.data.indexOf instanceof Function &&  response.data.indexOf('<html weixinOauth2Login>') != -1) {
                	$rootScope.wxstore.reLoginAlert();
                	//$location.path("/wxstore");
                	//window.location = "/wxstore"; // just in case
                	//$state.go('tabs.store');
                }
            }
	      return response || $q.when(response);
	    },

	    responseError: function(rejection) {
	      // Called when another XHR request returns with
	      // an error status code.

	      return $q.reject(rejection);
	    }

	  }
	  
}]);

WxStoreApp.config(["$httpProvider","$stateProvider","$urlRouterProvider","$ionicConfigProvider",
                   function($httpProvider, $stateProvider, $urlRouterProvider, $ionicConfigProvider) {
	//注入302重定向拦截器
	$httpProvider.interceptors.push('oauthInterceptor');
	
	//全局配置
	$ionicConfigProvider.platform.ios.tabs.style('standard'); 
    $ionicConfigProvider.platform.ios.tabs.position('bottom');
    $ionicConfigProvider.platform.android.tabs.style('standard');
    $ionicConfigProvider.platform.android.tabs.position('bottom');

    $ionicConfigProvider.platform.ios.navBar.alignTitle('center'); 
    $ionicConfigProvider.platform.android.navBar.alignTitle('center');

    $ionicConfigProvider.platform.ios.backButton.previousTitleText('').icon('ion-ios-arrow-thin-left');
    $ionicConfigProvider.platform.android.backButton.previousTitleText('').icon('ion-android-arrow-back');        

    $ionicConfigProvider.platform.ios.views.transition('ios');
    $ionicConfigProvider.platform.android.views.transition('android');

	 $stateProvider
	    .state('tabs', {
	      url: "/tab",
	      abstract: true,
	      templateUrl: "resources/templates/tabs.html"
	    })
	    .state('tabs.store', {
	      url: "/Store",
	      views: {
	        'store-tab': {
	             templateUrl: "resources/templates/store.html",
	             controller: 'StoreController'
	        }
	      }
	    })
	    .state('tabs.goodsDetail', {
	      url: "/GoodsDetail/:goodsId",//a 表情的href属性与此处的url对应
	      views: {
	        'store-tab': {//页面所属的tab
	             templateUrl: "resources/templates/store-goods-detail.html",//页面的位置
		         controller: 'StoreGoodsDetailController'//页面对应的前端的controller
	        }
	      }
	    })
	    .state('tabs.storeOrderConfirm', {
	      url: "/orderConfirm",
	      views: {
	        'store-tab': {
	             templateUrl: "resources/templates/order-confirm.html",
		         controller: 'OrderConfirmController'
	        }
	      }
	    })
	    //商城--订单--收获地址--管理收获地址
	    .state('tabs.orderManagerAddress', {
	       url: "/OrderManagerAddress",
	       views: {
	          'store-tab': {
	              templateUrl: "resources/templates/address-picker.html",
	              controller: 'AddressPickerController'
	          }
	       }
	    })
	    .state('tabs.cart', {
	      url: "/Cart",
	      cache:'false', 
	      views: {
	        'cart-tab': {
	             templateUrl: "resources/templates/cart.html",
	             controller: 'CartController'
	        }
	      }
	    })
	    .state('tabs.cartGoodsDetail', {
	      url: "/CartGoodsDetail/:goodsId",
	      views: {
	        'cart-tab': {
	             templateUrl: "resources/templates/cart-goods-detail.html",
	             controller: 'CartGoodsDetailController'
	        }
	      }
	    })
	    .state('tabs.cartOrderConfirm', {
	      url: "/orderConfirm",
	      views: {
	        'cart-tab': {
	        	 templateUrl: "resources/templates/order-confirm.html",
			     controller: 'OrderConfirmController'
	        }
	      }
	    })
	    //购物车--结算--收获地址--管理收获地址
	    .state('tabs.cartManagerAddress', {
	       url: "/CartManagerAddress",
	       views: {
	          'cart-tab': {
	              templateUrl: "resources/templates/address-picker.html",
	              controller: 'AddressPickerController'
	          }
	       }
	    })
	     .state('tabs.orders', {
	      url: "/Orders",
	      views: {
	        'orders-tab': {
	          templateUrl: "resources/templates/orders.html",
	          controller: 'OrdersController'
	        }
	      }
	    })
	    .state('tabs.orderGoodsDetail', {
		      url: "/OrderGoodsDetail/:goodsId",
		      views: {
		        'orders-tab': {
		          templateUrl: "resources/templates/cart-goods-detail.html",
		          controller: 'CartGoodsDetailController'
		        }
		      }
		 })
	    .state('tabs.myCenter', {
	      url: "/MyCenter",
	      views: {
	        'myCenter-tab': {
	          templateUrl: "resources/templates/my-center.html",
	          controller: 'MyCenterController'
	        }
	      }
	    })
	    .state('tabs.myAddress', {
	       url: "/MyAddress",
	       views: {
	          'myCenter-tab': {
	              templateUrl: "resources/templates/my-address-list.html",
	              controller: 'MyAddressController'
	          }
	       }
	    })


	   $urlRouterProvider.otherwise("/tab/Store");

	}]);

WxStoreApp.run(["$rootScope","$ionicLoading","$ionicPopup",function($rootScope, $ionicLoading, $ionicPopup){
		$rootScope.wxstore ={
				ctx : "wxstore",
				badgeData :{
					cartBadgeCount : 0,  //新加入购物车中的商品数量
					ordersBadgeCount : 0
				},
				cartNumber:0,  //购物车中的商品数量
				 
				//订单参数（通过设置全局变量，达到在两个controller之前传递对象类型的参数）
				orderVoListParam:{},
				orderFrom:"store",//订单页面的前一个页面：store:商城,cart:购物车。根据前一个页面所在tab弹出属于相应tab的addressPicker页面。
				
				//收货地址
				consigneeAddress:{},
				
				//加载蒙版 在前端可以防止重复提交
				showLoading : function() {
					$ionicLoading.show({
						template: '客官稍等，店小二玩命加载中...'
					});
				},
				hideLoading : function(){
					$ionicLoading.hide();
				},
				
				//错误信息 提示框
				showError : function(msg) {
					if(msg.errmsg && msg.errcode){
						msg='<h5 class="assertive">亲，出错啦！'+msg.errmsg+'</h5>';
					}
				    var alertPopup = $ionicPopup.alert({
				         title: '<h4 class="assertive">亲，出错啦！</h4>',
				         template: msg
				    });
				     
				    alertPopup.then(function(res) {
				         //console.log('Thank you for not eating my delicious ice cream cone');
				    });
				},
				
				//提示信息 提示框
				showAlert : function(msg) {
				     var alertPopup = $ionicPopup.alert({
				         title: '<h4 class="balanced">'+msg+'</h4>',
				         template: ""
				     });
				     
				     alertPopup.then(function(res) {
				         //console.log('Thank you for not eating my delicious ice cream cone');
				     });
				},
				
				//登录超时，点击确定将重新进入系统
				reLoginAlert : function() {
				     var alertPopup = $ionicPopup.alert({
				         title: '<h4 class="assertive">登录超时！</h4>',
				         okType:'button-positive',
				         okText:' 重 新 登 录 系 统 '
				     });
				     alertPopup.then(function(res) {
				    	 window.location = "/wxstore";
				     });
				}
				
		};
		
	}]);

